/**
 * User: Oleksii Savchenko
 * Date: 15.02.13
 * Time: 11:04
 */

var mainActions = {
    timeOpen: 150,
    timeClose:200,
    _id: null,
    _selector: null,
    baseUrl: 'http://localhost:3000/',

    /**
     * Open popup
     * @param selector
     */
    openPopup: function(selector, elem) {
        if(elem){
            this._id = zdom(elem).attr('data-id');
        }
        this._selector = selector;
        zdom(selector).show(this.timeOpen);
    },

    /**
     * Close popup
     * @param selector
     */
    closePopup: function(selector) {
        zdom(selector).hide(this.timeClose);
    },

    /**
     * Collects the data from the form
     * @param selector
     */
    addItem: function(selector){
        var formData = zdom(selector).serializeArray();
        this._setNewItem(formData);
    },

    _setNewItem: function(formData) {
        var self = this,
            ajaxService = new ItemAjaxService(self.baseUrl),
            item = {
                dimensions: {}
            };
        _.each(formData, function(val, key){
            if(key === 'name' || key === 'price' || key === 'image') {
                item[key] = val;
            } else {
                item.dimensions[key] = val;
            }
        });
        ajaxService.create(item, function(response){
            if(response){
                self.closePopup(self._selector);
                self.getItems();
            }
        });
    },

    /**
     * For Edit selected Item
     */
    editItem: function(elem) {
        var self = this,
            id = zdom(elem).attr('data-id'),
            dataBeforSave = {
                name:  zdom('#name-' + id).val(),
                price: zdom('#price-' + id).val(),
                lengths: zdom('#length-' + id).val(),
                width: zdom('#width-' + id).val(),
                height: zdom('#height-' + id).val()
            },
            dataForSave = {
                data: {
                    dimensions: {}
                },
                params: {id: id}
            };
            self._id = id;

        for(var key in dataBeforSave){
            if(dataBeforSave[key] === '' || dataBeforSave[key] === undefined) continue;
            if(key !== 'price' && key !== 'name') {
                dataForSave.data.dimensions[key] = dataBeforSave[key];
            } else {
                dataForSave.data[key] = dataBeforSave[key];
            }
        }

        self._setUpdatedData(dataForSave);
    },

    /**
     * Set updates to store
     * @param dataForSave
     */
    _setUpdatedData: function(dataForSave) {
        var self = this,
            ajaxService = new ItemAjaxService(self.baseUrl),
            id, elements;

        ajaxService.update(dataForSave, function(res){
            if(res){
                elements = document.getElementsByClassName('fch-' + self._id);
                _.each(elements, function(elem){
                    zdom(elem).visible(false);
                });
            }
        });
    },

    /**
     * Remove item
     */
    removeItem: function() {
        var self = this,
            ajaxService = new ItemAjaxService(self.baseUrl);

        ajaxService.delete([{id: self._id}], function(res){
            if(res){
                self.closePopup(self._selector);
                self.getItems();
            }
        });
    },

    /**
     * Load items
     * or reload items
     */
    getItems: function() {
        var self = this,
            ajaxService = new ItemAjaxService(self.baseUrl),
            itemList;

        ajaxService.getItemById({}, function(items){
            itemList = self._generateItems(items);
            zdom('#text-area').html(itemList);
        });
    },

    /**
     * Generate list of items
     * from template
     * @param items
     * @return {String}
     * @private
     */
    _generateItems: function(items) {
        var string = '<!--item-->' + "\n";
        _.each(items, function(item){
            if(!item.dimensions){
                item.dimensions = {
                    height: '',
                    lengths: '',
                    width: ''
                };
            }
            string += new EJS({url: 'js/itemTemplate.ejs'}).render(item);
        });
        return string;
    },

    /**
     * Show change icon
     * @param elem
     */
    showChangeIcon: function(elem) {
        var field = zdom(elem).attr('name'),
            id = zdom(elem).attr('id'),
            wornId = '#warn-' + id;

        zdom(wornId).visible(true);
    },

    /**
     * Load page with sorts param
     * @param elem
     */
    sortBy: function(elem) {
        var self = this,
            selItem = zdom(elem).val(),
            ajaxService = new ItemAjaxService(self.baseUrl),
            itemList;

        ajaxService.getItemById({sort: selItem}, function(items){
            itemList = self._generateItems(items);
            zdom('#text-area').html(itemList);
        });
    }
};